/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import EmployeeServer.Employee;
import Entity.MyEmployee;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.ws.rs.core.GenericEntity;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import rest.EmployeeRestClient;

/**
 *
 * @author HOANG ANH
 */
@ManagedBean
@SessionScoped
public class EmployeesRESTBean {

    private EmployeeRestClient rest;
    private String name, name2;
    private String country, country2;
    private Date birthDay, birthDay2;
    private boolean male, male2;
    private ArrayList<MyEmployee> empList = null;
    private MyEmployee employee;

    /** Creates a new instance of EmployeesRESTBean */
    public EmployeesRESTBean() {
    }

    private void updateList() {
        try {
            rest = new EmployeeRestClient();
            ClientResponse clientResponse = rest.getXml_XML(ClientResponse.class);
            String xmlGet = clientResponse.getEntity(String.class);
            rest.close();
            InputSource source = new InputSource(new StringReader(xmlGet));
            Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source);
            NodeList employeeNodes = dom.getElementsByTagName("employee");
            empList = new ArrayList<MyEmployee>();
            for (int i = 0; i < employeeNodes.getLength(); i++) {
                Element element = (Element) employeeNodes.item(i);
                MyEmployee emp = new MyEmployee();
                emp.setName(element.getElementsByTagName("name").item(0).getTextContent());
                emp.setCountry(element.getElementsByTagName("country").item(0).getTextContent());
                emp.setMale(Boolean.valueOf(element.getElementsByTagName("male").item(0).getTextContent()));
                String d = element.getElementsByTagName("birthday").item(0).getTextContent();
                XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(d);
                emp.setBirthday(xmlCal);
                empList.add(emp);
            }
        } catch (Exception ex) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "This is not my fault. Go ask my service provider.", ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, msg);
            ex.printStackTrace();
        }
    }

    public Date getToday() {
        return new Date();
    }

    public Date getBirthDay() {
        return birthDay;
    }

    public void setBirthDay(Date birthDay) {
        this.birthDay = birthDay;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public boolean isMale() {
        return male;
    }

    public void setMale(boolean male) {
        this.male = male;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ArrayList<MyEmployee> getEmpList() {
        if (empList == null) {
            updateList();
        }
        return empList;
    }

    public void setEmpList(ArrayList<MyEmployee> empList) {
        this.empList = empList;
    }

    public void register() {
        try {
            Date today = new Date();
            if (name.length() < 2) {
                throw new Exception("Your name is way too short O_o");
            }
            if (country.length() < 2) {
                throw new Exception("Your country's name only have 1 syllabel ???");
            }
            if (birthDay.after(today)) {
                throw new Exception("Sorry mom. We ain't gonna hire your unborn child -.-");
            }
            if ((today.getYear() - birthDay.getYear()) > 60) {
                throw new Exception("You are too old... Please retire.");
            } else if ((today.getYear() - birthDay.getYear()) < 16) {
                throw new Exception("You are too young... Go play somewhere else.");
            }


            Employee emp = new Employee();
            emp.setName(name);
            emp.setCountry(country);
            emp.setMale(male);

            GregorianCalendar c = new GregorianCalendar();
            c.setTime(birthDay);
            XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);

            String input = "<employee><name>" + name + "</name><country>" + country + "</country>"
                    + "<birthday>" + date2.toString() + "</birthday><male>" + male + "</male></employee>";
            rest = new EmployeeRestClient();
            rest.postXml_XML(input);
            rest.close();
            updateList();
            name = "";
            country = "";
            birthDay = today;
        } catch (DatatypeConfigurationException ex) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERORR", ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (Exception ex) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Bang! ", ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    }
}
